import React, { useState, useRef, useEffect } from 'react';
import { toast } from '@/lib/toast-with-audio';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, PieChart, Pie, Cell, Legend, LineChart, Line } from 'recharts';
import { cn } from '@/lib/utils';
import { motion, AnimatePresence } from 'framer-motion';
import { taskApi } from '@/store/task';
import type { Task, GetTasksParams } from '@/types/task';
import DetailDrawer from '@/components/DetailDrawer';
import {
  DndContext,
  closestCenter,
  KeyboardSensor,
  PointerSensor,
  useSensor,
  useSensors,
  DragEndEvent,
  DragOverEvent,
  DragStartEvent,
  DragOverlay
} from '@dnd-kit/core';
import {
  arrayMove,
  SortableContext,
  sortableKeyboardCoordinates,
  verticalListSortingStrategy,
  horizontalListSortingStrategy
} from '@dnd-kit/sortable';
import {
  useSortable
} from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';

// 使用导入的Task类型，不再需要本地定义

// 任务状态分布数据
const statusDistributionData = [
  { name: '待开发', value: 15, color: '#9ca3af' },
  { name: '开发中', value: 22, color: '#3b82f6' },
  { name: '待测试', value: 10, color: '#8b5cf6' },
  { name: '已完成', value: 25, color: '#10b981' },
];

// 任务完成趋势数据
const completionTrendData = [
  { date: '2/26', 计划完成: 8, 实际完成: 6 },
  { date: '2/27', 计划完成: 10, 实际完成: 8 },
  { date: '2/28', 计划完成: 12, 实际完成: 10 },
  { date: '2/29', 计划完成: 8, 实际完成: 9 },
  { date: '3/1', 计划完成: 10, 实际完成: 7 },
  { date: '3/2', 计划完成: 12, 实际完成: 11 },
  { date: '3/3', 计划完成: 10, 实际完成: 9 },
];

// 状态徽章组件
const StatusBadge: React.FC<{ status: string }> = ({ status }) => {
  const statusMap: Record<string, { bg: string, text: string }> = {
    '待开发': { bg: 'bg-gray-100', text: 'text-gray-700' },
    '开发中': { bg: 'bg-blue-100', text: 'text-blue-700' },
    '待测试': { bg: 'bg-purple-100', text: 'text-purple-700' },
    '已完成': { bg: 'bg-green-100', text: 'text-green-700' },
    '已拒绝': { bg: 'bg-red-100', text: 'text-red-700' },
    '进行中': { bg: 'bg-blue-100', text: 'text-blue-700' },
  };
  
  const style = statusMap[status] || { bg: 'bg-gray-100', text: 'text-gray-700' };
  
  return (
    <span className={`px-2 py-1 text-xs font-medium rounded-full ${style.bg} ${style.text}`}>
      {status}
    </span>
  );
};

// 优先级标签组件
const PriorityTag: React.FC<{ priority: string }> = ({ priority }) => {
  const priorityMap: Record<string, { bg: string, text: string }> = {
    '高': { bg: 'bg-red-100', text: 'text-red-700' },
    '中': { bg: 'bg-amber-100', text: 'text-amber-700' },
    '低': { bg: 'bg-gray-100', text: 'text-gray-700' },
  };
  
  const style = priorityMap[priority] || { bg: 'bg-gray-100', text: 'text-gray-700' };
  
  return (
    <span className={`px-2 py-1 text-xs font-medium rounded-full ${style.bg} ${style.text}`}>
      {priority}
    </span>
  );
};

// 类别标签组件
const CategoryTag: React.FC<{ category: string }> = ({ category }) => {
  return (
    <span className="px-2 py-1 text-xs bg-gray-100 rounded-full text-gray-700">
      {category}
    </span>
  );
};

// 进度条组件
const ProgressBar: React.FC<{ progress: number }> = ({ progress }) => {
  let color = '#3b82f6'; // 默认蓝色
  
  if (progress === 0) {
    color = '#d1d5db'; // 灰色表示未开始
  } else if (progress === 100) {
    color = '#10b981'; // 绿色表示已完成
  } else if (progress > 75) {
    color = '#22c55e'; // 浅绿色表示即将完成
  }
  
  return (
    <div className="w-full bg-gray-200 rounded-full h-2">
      <div 
        className="h-2 rounded-full transition-all duration-500 ease-out" 
        style={{ width: `${progress}%`, backgroundColor: color }}
      ></div>
    </div>
  );
};

// 用户头像组件
const UserAvatar: React.FC<{ name: string }> = ({ name }) => {
  if (!name) {
    return (
      <div className="w-7 h-7 rounded-full bg-gray-100 flex items-center justify-center text-xs font-medium text-gray-500">
        <i className="fa-solid fa-user"></i>
      </div>
    );
  }
  
  // 从姓名中提取第一个字符
  const initial = name.charAt(0).toUpperCase();
  
  // 为不同的姓氏生成不同的背景色
  const colors = [
    'bg-blue-100 text-blue-600',
    'bg-green-100 text-green-600',
    'bg-purple-100 text-purple-600',
    'bg-amber-100 text-amber-600',
    'bg-pink-100 text-pink-600',
    'bg-indigo-100 text-indigo-600'
  ];
  
  // 简单的哈希函数来选择颜色
  const hash = name.split('').reduce((acc, char) => acc + char.charCodeAt(0), 0);
  const colorClass = colors[hash % colors.length];
  
  return (
    <div className={`w-7 h-7 rounded-full ${colorClass} flex items-center justify-center text-xs font-medium`}>
      {initial}
    </div>
  );
};

export default function Tasks() {
  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');
  const [priorityFilter, setPriorityFilter] = useState('all');
  const [assigneeFilter, setAssigneeFilter] = useState('all');
  const [viewMode, setViewMode] = useState<'list' | 'board'>('list');
  const [tasks, setTasks] = useState<Task[]>([]);
  const [loading, setLoading] = useState(true);
  const [isDrawerOpen, setIsDrawerOpen] = useState(false);
  const [selectedTask, setSelectedTask] = useState<Task | null>(null);
  const [activeTask, setActiveTask] = useState<Task | null>(null);
  
  // 配置传感器
  const sensors = useSensors(
    useSensor(PointerSensor),
    useSensor(KeyboardSensor, {
      coordinateGetter: sortableKeyboardCoordinates,
    })
  );
  
  // 加载任务数据
  useEffect(() => {
    const loadTasks = async () => {
      try {
        setLoading(true);
        const response = await taskApi.getTasks();
        if (response.success) {
          setTasks(response.data);
        } else {
          toast.error(response.message || '获取任务列表失败');
        }
      } catch (error) {
        console.error('加载任务数据失败:', error);
        toast.error('加载任务数据失败');
      } finally {
        setLoading(false);
      }
    };

    loadTasks();
  }, []);

  // 获取所有可能的分配人
  const assignees = ['all', ...Array.from(new Set(tasks.map(task => task.assignee).filter(Boolean)))];
  
  // 看板列定义
  const columns = [
    { status: '待开发', color: 'bg-gray-100 dark:bg-gray-800' },
    { status: '开发中', color: 'bg-blue-100 dark:bg-blue-900' },
    { status: '待测试', color: 'bg-purple-100 dark:bg-purple-900' },
    { status: '已完成', color: 'bg-green-100 dark:bg-green-900' },
  ];

  // 展开/折叠任务
  const toggleExpand = (taskId: number) => {
    setTasks(prevTasks => prevTasks.map(task => 
      task.id === taskId 
        ? { ...task, isExpanded: !task.isExpanded } 
        : task
    ));
  };

  // 处理查看任务详情
  const handleViewTask = (task: Task) => {
    setSelectedTask(task);
    setIsDrawerOpen(true);
  };

  // 处理编辑任务
  const handleEditTask = (task: Task) => {
    setSelectedTask(task);
    setIsDrawerOpen(true);
  };

  // 处理抽屉关闭
  const handleDrawerClose = () => {
    setIsDrawerOpen(false);
    setSelectedTask(null);
  };

  // 递归渲染树表行
  const renderTreeRows = (tasks: Task[], level = 0) => {
    const rows: JSX.Element[] = [];
    
    tasks.forEach(task => {
      // 渲染当前任务
      rows.push(
        <tr key={task.id} className="hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors">
          <td className="px-6 py-4 whitespace-nowrap">
            <div className="flex items-center" style={{ paddingLeft: `${level * 24}px` }}>
              {task.children && task.children.length > 0 ? (
                <button 
                  onClick={() => toggleExpand(task.id)}
                  className="mr-2 text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300"
                >
                  <i className={`fa-solid ${task.isExpanded ? 'fa-chevron-down' : 'fa-chevron-right'}`}></i>
                </button>
              ) : (
                <span className="mr-6"></span>
              )}
              <div className="font-mono text-sm text-gray-600 dark:text-gray-300 font-medium">{task.code}</div>
            </div>
          </td>
          <td className="px-6 py-4">
            <div className={`font-medium ${task.isOverdue ? 'text-red-600 dark:text-red-400' : 'text-gray-900 dark:text-gray-100'}`}>
              {task.title}
              {task.isOverdue && <span className="ml-2 text-red-500 dark:text-red-400"><i className="fa-solid fa-circle-exclamation"></i></span>}
            </div>
            <div className="flex items-center mt-1">
              <CategoryTag category={task.category} />
            </div>
          </td>
          <td className="px-6 py-4 whitespace-nowrap">
            <span className="px-2 py-1 text-xs bg-gray-100 dark:bg-gray-600 rounded-full text-gray-800 dark:text-gray-100">
              {task.project}
            </span>
          </td>
          <td className="px-6 py-4 whitespace-nowrap">
            <StatusBadge status={task.status} />
          </td>
          <td className="px-6 py-4 whitespace-nowrap">
            <PriorityTag priority={task.priority} />
          </td>
          <td className="px-6 py-4 whitespace-nowrap">
            <div className="flex items-center">
              <UserAvatar name={task.assignee} />
              <span className="ml-2 text-sm text-gray-800 dark:text-gray-100">{task.assignee || '未分配'}</span>
            </div>
          </td>
          <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400">
            {task.deadline}
          </td>
          <td className="px-6 py-4 whitespace-nowrap">
            <div className="flex items-center">
              <ProgressBar progress={task.progress} />
              <span className="ml-3 text-sm font-medium text-gray-700 dark:text-gray-300">{task.progress}%</span>
            </div>
          </td>
          <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
            <button 
              className="text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300 mr-4"
              onClick={() => handleViewTask(task)}
            >
              <i className="fa-solid fa-eye mr-1"></i>详情
            </button>
            <button 
              className="text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300 mr-4"
              onClick={() => handleEditTask(task)}
            >
              <i className="fa-solid fa-pen-to-square mr-1"></i>编辑
            </button>
            {task.status !== '已完成' && (
              <button 
                className="text-green-600 dark:text-green-400 hover:text-green-800 dark:hover:text-green-300"
                onClick={() => handleMarkComplete(task.id)}
              >
                <i className="fa-solid fa-check mr-1"></i>完成
              </button>
            )}
          </td>
        </tr>
      );
      
      // 如果任务有子任务且已展开，递归渲染子任务
      if (task.children && task.isExpanded) {
        rows.push(...renderTreeRows(task.children, level + 1));
      }
    });
    
    return rows;
  };
  
  // 过滤任务数据
  const filteredTasks = tasks.filter(task => {
    const matchesSearch = 
      task.title.toLowerCase().includes(searchTerm.toLowerCase()) || 
      task.code.toLowerCase().includes(searchTerm.toLowerCase()) ||
      (task.assignee && task.assignee.toLowerCase().includes(searchTerm.toLowerCase()));
    
    const matchesStatus = statusFilter === 'all' || task.status === statusFilter;
    const matchesPriority = priorityFilter === 'all' || task.priority === priorityFilter;
    const matchesAssignee = assigneeFilter === 'all' || task.assignee === assigneeFilter;
    
    return matchesSearch && matchesStatus && matchesPriority && matchesAssignee;
  });
  


  // 搜索处理函数
  const handleSearch = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      // 搜索逻辑
      toast.info(`搜索: ${searchTerm}`);
    }
  };

  // 创建任务处理函数
  const handleCreateTask = () => {
    toast.success('创建新任务');
  };

  // 标记完成任务处理函数
  const handleMarkComplete = (id: number) => {
    toast.success('任务已标记为完成');
  };

  // 任务卡片组件
  const TaskCard = ({ task }: { task: Task }) => {
    return (
      <motion.div
        draggable={true}
        whileHover={{ scale: 1.02 }}
        whileDrag={{ scale: 0.98, opacity: 0.8 }}
        onDragStart={(e) => handleDragStart(e, task.id)}
        onDragEnd={() => {
          setDraggedTask(null);
          setIsDragging(false);
        }}
        className="bg-white dark:bg-gray-700 rounded-lg shadow-sm border border-gray-200 dark:border-gray-600 p-4 mb-3 cursor-move hover:shadow-md transition-shadow"
      >
        <div className="flex justify-between items-start mb-2">
          <span className="text-xs font-mono text-gray-500 dark:text-gray-400">{task.code}</span>
          <PriorityTag priority={task.priority} />
        </div>
        <h4 className={`font-medium mb-2 ${task.isOverdue ? 'text-red-600 dark:text-red-400' : 'text-gray-800 dark:text-gray-100'}`}>
          {task.title}
          {task.isOverdue && <span className="ml-1 text-red-500 dark:text-red-400"><i className="fa-solid fa-circle-exclamation text-xs"></i></span>}
        </h4>
        <div className="flex justify-between items-center">
          {task.assignee ? (
            <div className="flex items-center">
              <UserAvatar name={task.assignee} />
              <span className="text-xs text-gray-600 dark:text-gray-300 ml-1">{task.assignee}</span>
            </div>
          ) : (
            <span className="text-xs text-gray-500 dark:text-gray-400">未分配</span>
          )}
          <CategoryTag category={task.category} />
        </div>
      </motion.div>
    );
  };



  // 创建新的SortableTaskCard组件
  const SortableTaskCard = ({ task }: { task: Task }) => {
    const {
      attributes,
      listeners,
      setNodeRef,
      transform,
      transition,
      isDragging,
    } = useSortable({ id: task.id });
    
    const style = {
      transform: CSS.Transform.toString(transform),
      transition,
    };

    return (
      <motion.div
        ref={setNodeRef}
        style={style}
        {...attributes}
        {...listeners}
        whileHover={{ scale: 1.02 }}
        whileDrag={{ scale: 0.98, opacity: 0.8 }}
        className={`bg-white dark:bg-gray-700 rounded-lg shadow-sm border border-gray-200 dark:border-gray-600 p-4 mb-3 cursor-move hover:shadow-md transition-shadow ${
          isDragging ? 'opacity-50' : ''
        }`}
      >
        <div className="flex justify-between items-start mb-2">
          <span className="text-xs font-mono text-gray-500 dark:text-gray-400">{task.code}</span>
          <PriorityTag priority={task.priority} />
        </div>
        <h4 className={`font-medium mb-2 ${task.isOverdue ? 'text-red-600 dark:text-red-400' : 'text-gray-800 dark:text-gray-100'}`}>
          {task.title}
          {task.isOverdue && <span className="ml-1 text-red-500 dark:text-red-400"><i className="fa-solid fa-circle-exclamation text-xs"></i></span>}
        </h4>
        <div className="flex justify-between items-center">
          {task.assignee ? (
            <div className="flex items-center">
              <UserAvatar name={task.assignee} />
              <span className="text-xs text-gray-600 dark:text-gray-300 ml-1">{task.assignee}</span>
            </div>
          ) : (
            <span className="text-xs text-gray-500 dark:text-gray-400">未分配</span>
          )}
          <CategoryTag category={task.category} />
        </div>
      </motion.div>
    );
  };

  // 创建用于DragOverlay的卡片组件
  const TaskCardForOverlay = ({ task }: { task: Task }) => {
    return (
      <div className="bg-white dark:bg-gray-700 rounded-lg shadow-lg border border-blue-300 dark:border-blue-400 p-4 w-[260px] transform rotate-3 opacity-90">
        <div className="flex justify-between items-start mb-2">
          <span className="text-xs font-mono text-gray-500 dark:text-gray-400">{task.code}</span>
          <PriorityTag priority={task.priority} />
        </div>
        <h4 className={`font-medium mb-2 ${task.isOverdue ? 'text-red-600 dark:text-red-400' : 'text-gray-800 dark:text-gray-100'}`}>
          {task.title}
          {task.isOverdue && <span className="ml-1 text-red-500 dark:text-red-400"><i className="fa-solid fa-circle-exclamation text-xs"></i></span>}
        </h4>
        <div className="flex justify-between items-center">
          {task.assignee ? (
            <div className="flex items-center">
              <UserAvatar name={task.assignee} />
              <span className="text-xs text-gray-600 dark:text-gray-300 ml-1">{task.assignee}</span>
            </div>
          ) : (
            <span className="text-xs text-gray-500 dark:text-gray-400">未分配</span>
          )}
          <CategoryTag category={task.category} />
        </div>
      </div>
    );
  };

  // 创建新的SortableColumn组件
  const SortableColumn = ({ status, color }: { status: string, color: string }) => {
    const columnTasks = tasks.filter(task => task.status === status);
    
    const {
      attributes,
      listeners,
      setNodeRef,
      transform,
      transition,
      isDragging,
    } = useSortable({ id: status });
    
    const style = {
      transform: CSS.Transform.toString(transform),
      transition,
    };
    
    return (
      <div 
        ref={setNodeRef}
        style={style}
        {...attributes}
        {...listeners}
        className={`flex-1 min-w-[280px] max-w-[280px] ${color} rounded-lg p-3 mr-3 overflow-y-auto max-h-[calc(100vh-260px)] min-h-[400px] ${
          isDragging ? 'opacity-50' : ''
        }`}
      >
        <div className="flex justify-between items-center mb-3">
          <h3 className="font-medium dark:text-gray-100">{status}</h3>
          <span className="bg-white dark:bg-gray-600 text-gray-700 dark:text-gray-300 text-xs font-medium px-2 py-1 rounded-full">
            {columnTasks.length}
          </span>
        </div>
        <SortableContext items={columnTasks.map(task => task.id)} strategy={verticalListSortingStrategy}>
          <div>
            <AnimatePresence>
              {columnTasks.map(task => (
                <SortableTaskCard key={task.id} task={task} />
              ))}
            </AnimatePresence>
          </div>
        </SortableContext>
      </div>
    );
  };

  // 拖拽开始事件处理
  const handleDragStart = (event: DragStartEvent) => {
    const { active } = event;
    const task = tasks.find(t => t.id === active.id);
    setActiveTask(task || null);
  };

  // 拖拽结束事件处理
  const handleDragEnd = (event: DragEndEvent) => {
    const { active, over } = event;
    
    if (!over) {
      setActiveTask(null);
      return;
    }

    const activeTask = tasks.find(t => t.id === active.id);
    
    // 检查是否拖拽到了列上
    const overColumn = columns.find(col => col.status === over.id);
    
    if (activeTask && overColumn) {
      // 更新任务状态
      setTasks(prevTasks => 
        prevTasks.map(task => 
          task.id === active.id 
            ? { 
                ...task, 
                status: overColumn.status,
                progress: overColumn.status === '已完成' ? 100 : task.progress 
              } 
            : task
        )
      );
      toast(`任务已移动到 ${overColumn.status} 状态`);
    }
    
    setActiveTask(null);
  };

  // 拖拽悬停事件处理
  const handleDragOver = (event: DragOverEvent) => {
    // 可以在这里添加悬停效果
  };

  return (
    <div>
       <div className="mb-6">
        <motion.div 
          className="mb-8"
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5 }}
        >
         <h1 className="text-2xl font-bold text-gray-800 dark:text-gray-100">任务管理</h1>
         <p className="text-gray-600 dark:text-gray-400 mt-1">管理所有项目任务的创建、分配、跟踪和完成</p>
        </motion.div>
       </div>
       
       {/* 视图切换 */}
       <div className="flex justify-between items-center mb-4">
         <div className="flex items-center space-x-2 bg-gray-100 dark:bg-gray-700 rounded-lg p-1">
           <button 
             className={`px-3 py-1 rounded-md text-sm font-medium transition-colors ${viewMode === 'list' ? 'bg-white dark:bg-gray-600 shadow-sm text-blue-600 dark:text-blue-400' : 'text-gray-600 dark:text-gray-400'}`}
             onClick={() => setViewMode('list')}
           >
             <i className="fa-solid fa-list mr-1"></i>列表视图
           </button>
           <button 
             className={`px-3 py-1 rounded-md text-sm font-medium transition-colors ${viewMode === 'board' ? 'bg-white dark:bg-gray-600 shadow-sm text-blue-600 dark:text-blue-400' : 'text-gray-600 dark:text-gray-400'}`}
             onClick={() => setViewMode('board')}
           >
             <i className="fa-solid fa-columns mr-1"></i>看板视图
           </button>
         </div>
         
         <button 
           className="flex items-center bg-blue-600 hover:bg-blue-700 text-white py-2 px-4 rounded-lg transition-colors duration-300"
           onClick={handleCreateTask}
         >
           <i className="fa-solid fa-plus mr-2"></i>
           新建任务
         </button>
       </div>
      
      {/* 任务概览卡片 */}
      <div className="grid grid-cols-4 gap-6 mb-6">
        <motion.div 
          initial={{ opacity: 0, scale: 0.95 }}
          animate={{ opacity: 1, scale: 1 }}
          transition={{ duration: 0.3 }}
          className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-5 hover:shadow-md transition-shadow"
        >
          <div className="flex items-center justify-between mb-3">
            <h3 className="text-sm font-medium text-gray-500 dark:text-gray-400">总任务数</h3>
            <i className="fa-solid fa-list-check text-blue-500"></i>
          </div>
          <div className="flex items-end justify-between">
            <p className="text-3xl font-bold text-gray-900 dark:text-gray-100">{tasks.length}</p>
            <p className="text-sm text-green-600 dark:text-green-400 flex items-center">
              <i className="fa-solid fa-arrow-up mr-1"></i>12%
            </p>
          </div>
        </motion.div>
        
        <motion.div 
          initial={{ opacity: 0, scale: 0.95 }}
          animate={{ opacity: 1, scale: 1 }}
          transition={{ duration: 0.3, delay: 0.1 }}
          className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-5 hover:shadow-md transition-shadow">
          <div className="flex items-center justify-between mb-3">
            <h3 className="text-sm font-medium text-gray-500 dark:text-gray-400">进行中任务</h3>
            <i className="fa-solid fa-spinner text-blue-500"></i>
          </div>
          <div className="flex items-end justify-between">
            <p className="text-3xl font-bold text-gray-900 dark:text-gray-100">
              {tasks.filter(t => t.status === '开发中' || t.status === '待测试').length}
            </p>
            <p className="text-sm text-green-600 dark:text-green-400 flex items-center">
              <i className="fa-solid fa-arrow-up mr-1"></i>8%
            </p>
          </div>
        </motion.div>
        
        <motion.div 
          initial={{ opacity: 0, scale: 0.95 }}
          animate={{ opacity: 1, scale: 1 }}
          transition={{ duration: 0.3, delay: 0.2 }}
          className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-5 hover:shadow-md transition-shadow">
          <div className="flex items-center justify-between mb-3">
            <h3 className="text-sm font-medium text-gray-500 dark:text-gray-400">已完成任务</h3>
            <i className="fa-solid fa-check-circle text-green-500"></i>
          </div>
          <div className="flex items-end justify-between">
            <p className="text-3xl font-bold text-gray-900 dark:text-gray-100">
              {tasks.filter(t => t.status === '已完成').length}
            </p>
            <p className="text-sm text-green-600 dark:text-green-400 flex items-center">
              <i className="fa-solid fa-arrow-up mr-1"></i>20%
            </p>
          </div>
        </motion.div>
        
        <motion.div 
          initial={{ opacity: 0, scale: 0.95 }}
          animate={{ opacity: 1, scale: 1 }}
          transition={{ duration: 0.3, delay: 0.3 }}
          className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-5 hover:shadow-md transition-shadow">
          <div className="flex items-center justify-between mb-3">
            <h3 className="text-sm font-medium text-gray-500 dark:text-gray-400">逾期任务</h3>
            <i className="fa-solid fa-triangle-exclamation text-red-500"></i>
          </div>
          <div className="flex items-end justify-between">
            <p className="text-3xl font-bold text-gray-900 dark:text-gray-100">
              {tasks.filter(t => t.isOverdue).length}
            </p>
            <p className="text-sm text-red-600 dark:text-red-400 flex items-center">
              <i className="fa-solid fa-arrow-up mr-1"></i>5%
            </p>
          </div>
        </motion.div>
      </div>
      
       {/* 仅在列表视图显示图表和工具栏 */}
       {viewMode === 'list' && (
         <>
           {/* 图表区域 */}
           <div className="grid grid-cols-2 gap-6 mb-6">
             {/* 任务状态分布 */}
             <motion.div 
               initial={{ opacity: 0, scale: 0.95 }}
               animate={{ opacity: 1, scale: 1 }}
               transition={{ duration: 0.3, delay: 0.4 }}
               className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-5">
               <h2 className="text-lg font-semibold text-gray-800 dark:text-gray-100 mb-4">任务状态分布</h2>
               <div className="h-64">
                 <ResponsiveContainer width="100%" height="100%">
                   <PieChart>
                     <Pie
                       data={statusDistributionData}
                       cx="50%"
                       cy="50%"
                       innerRadius={60}
                       outerRadius={80}
                       fill="#8884d8"
                       paddingAngle={2}
                       dataKey="value"
                       label={({ name, value }) => `${name} ${value}`}
                       labelLine={false}
                     >
                       {statusDistributionData.map((entry, index) => (
                         <Cell key={`cell-${index}`} fill={entry.color} />
                       ))}
                     </Pie>
                     <Tooltip formatter={(value, name) => [`${value}个任务`, name]} />
                     <Legend verticalAlign="bottom" height={36} />
                   </PieChart>
                 </ResponsiveContainer>
               </div>
             </motion.div>
             
             {/* 任务完成趋势 */}
             <motion.div 
               initial={{ opacity: 0, scale: 0.95 }}
               animate={{ opacity: 1, scale: 1 }}
               transition={{ duration: 0.3, delay: 0.5 }}
               className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-5">
               <h2 className="text-lg font-semibold text-gray-800 dark:text-gray-100 mb-4">任务完成趋势</h2>
               <div className="h-64">
                 <ResponsiveContainer width="100%" height="100%">
                   <LineChart data={completionTrendData} margin={{ top: 5, right: 20, bottom: 5, left: 0 }}>
                     <CartesianGrid strokeDasharray="3 3" vertical={false} />
                     <XAxis dataKey="date" />
                     <YAxis />
                     <Tooltip formatter={(value) => [`${value}个任务`, '']} />
                     <Legend verticalAlign="top" height={36} />
                     <Line type="monotone" dataKey="计划完成" stroke="#94a3b8" strokeWidth={2} dot={{ r: 4 }} activeDot={{ r: 6 }} />
                     <Line type="monotone" dataKey="实际完成" stroke="#3b82f6" strokeWidth={2} dot={{ r: 4 }} activeDot={{ r: 6 }} />
                   </LineChart>
                 </ResponsiveContainer>
               </div>
             </motion.div>
           </div>
           
           {/* 工具栏 */}
           <motion.div 
             initial={{ opacity: 0, y: 20 }}
             animate={{ opacity: 1, y: 0 }}
             transition={{ duration: 0.3, delay: 0.6 }}
             className="flex flex-wrap justify-between items-center gap-4 mb-6">
             <div className="flex items-center space-x-4 flex-wrap gap-2">
               <div className="relative">
                 <input 
                   type="text" 
                   placeholder="搜索任务..." 
                   className="py-2 pl-10 pr-4 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent w-64 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
                   value={searchTerm}
                   onChange={(e) => setSearchTerm(e.target.value)}
                   onKeyDown={handleSearch}
                 />
                 <i className="fa-solid fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 dark:text-gray-500"></i>
               </div>
               
               <select 
                 className="py-2 pl-3 pr-8 border border-gray-300 dark:border-gray-600 rounded-lg appearance-none focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
                 value={statusFilter}
                 onChange={(e) => setStatusFilter(e.target.value)}
               >
                 <option value="all">全部状态</option>
                 <option value="待开发">待开发</option>
                 <option value="开发中">开发中</option>
                 <option value="待测试">待测试</option>
                 <option value="已完成">已完成</option>
               </select>
               
               <select 
                 className="py-2 pl-3 pr-8 border border-gray-300 dark:border-gray-600 rounded-lg appearance-none focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
                 value={priorityFilter}
                 onChange={(e) => setPriorityFilter(e.target.value)}
               >
                 <option value="all">全部优先级</option>
                 <option value="高">高</option>
                 <option value="中">中</option>
                 <option value="低">低</option>
               </select>
               
               <select 
                 className="py-2 pl-3 pr-8 border border-gray-300 dark:border-gray-600 rounded-lg appearance-none focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
                 value={assigneeFilter}
                 onChange={(e) => setAssigneeFilter(e.target.value)}
               >
                 <option value="all">全部负责人</option>
                 {assignees.map(assignee => (
                   <option key={assignee} value={assignee}>{assignee}</option>
                 ))}
               </select>
             </div>
           </motion.div>
         </>
       )}
      
       {/* 根据视图模式显示不同内容 */}
       {viewMode === 'board' ? (
         /* 看板视图 */
         <div className="bg-white dark:bg-gray-900 rounded-lg shadow-sm p-4 min-h-[500px]">
           <DndContext
             sensors={sensors}
             collisionDetection={closestCenter}
             onDragStart={handleDragStart}
             onDragEnd={handleDragEnd}
             onDragOver={handleDragOver}
           >
             <div className="overflow-x-auto pb-4 flex">
               <SortableContext items={columns.map(col => col.status)} strategy={horizontalListSortingStrategy}>
                 {columns.map((column) => (
                   <SortableColumn key={column.status} status={column.status} color={column.color} />
                 ))}
               </SortableContext>
             </div>
             <DragOverlay>
               {activeTask ? <TaskCardForOverlay task={activeTask} /> : null}
             </DragOverlay>
           </DndContext>
         </div>
       ) : (
         /* 列表视图 */
         <motion.div 
           initial={{ opacity: 0, scale: 0.95 }}
           animate={{ opacity: 1, scale: 1 }}
           transition={{ duration: 0.3, delay: 0.7 }}
           className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 overflow-hidden">
           <div className="overflow-x-auto">
             <table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
               <thead className="bg-gray-50 dark:bg-gray-700">
                 <tr>
                   <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">任务编号</th>
                   <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">任务名称</th>
                   <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">所属项目</th>
                   <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">状态</th>
                   <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">优先级</th>
                   <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">负责人</th>
                   <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">截止日期</th>
                   <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">进度</th>
                   <th scope="col" className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">操作</th>
                 </tr>
               </thead>
               <tbody className="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
                 {renderTreeRows(filteredTasks.filter(task => !task.parentId))}
               </tbody>
             </table>
           </div>
           
           {/* 分页 */}
           <div className="px-6 py-4 border-t border-gray-200 dark:border-gray-700 flex justify-between items-center">
             <div className="text-sm text-gray-500 dark:text-gray-400">显示 1 至 {filteredTasks.length} 条，共 {tasks.length} 条</div>
             <div className="flex space-x-2">
               <button className="px-3 py-1 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-500 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-600 disabled:opacity-50 disabled:cursor-not-allowed" disabled>
                 <i className="fa-solid fa-chevron-left text-xs"></i>
               </button>
               <button className="px-3 py-1 border border-blue-500 dark:border-blue-400 bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 rounded-md">1</button>
               <button className="px-3 py-1 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-600">
                 <i className="fa-solid fa-chevron-right text-xs"></i>
               </button>
             </div>
           </div>
         </motion.div>
       )}
       
       {/* 任务详情抽屉 */}
       <DetailDrawer 
         isOpen={isDrawerOpen}
         onClose={handleDrawerClose}
         item={selectedTask ? {
           ...selectedTask,
           type: 'task'
         } : null}
       />
     </div>
  );
}